<script setup>
import { ref } from 'vue';
import {
  ElMessage,
  ElUpload,
  ElButton,
  ElInput,
  ElInputNumber,
  ElForm,
  ElFormItem,
  ElCard,
  ElIcon,
  ElRow,
  ElCol,
  ElDivider,
} from 'element-plus';
import { Plus, ArrowLeft } from '@element-plus/icons-vue';
import courseService from '@/services/courseService.js';
import { useRouter } from 'vue-router';
import { userManager } from "@/utils/user.js";

const router = useRouter();

// --- 表单数据 ---
const courseForm = ref({
  name: '',
  description: '',
  school: '',
  credit: 0,
});
const submitting = ref(false);

// --- 封面图片上传相关 ---
const coverImageUploadRef = ref(null);
const coverImageList = ref([]);
const uploadedRawCoverImage = ref(null);

// --- 封面图片上传处理 ---
const handleCoverImageChange = (uploadFile) => {
  if (uploadFile.status === 'ready') {
    if (coverImageList.value.length > 0) {
      coverImageUploadRef.value.handleRemove(coverImageList.value[0]);
    }
    uploadedRawCoverImage.value = uploadFile.raw;
    coverImageList.value = [uploadFile];
  } else if (uploadFile.status === 'fail') {
    ElMessage.error({ message: `封面图片 ${uploadFile.name} 上传失败！`, offset: 80 });
    uploadedRawCoverImage.value = null;
    coverImageList.value = [];
  }
};

const handleCoverImageRemove = () => {
  uploadedRawCoverImage.value = null;
  coverImageList.value = [];
};

// --- 提交表单 ---
const submitForm = async () => {
  if (!courseForm.value.name) {
    ElMessage.warning({ message: '请输入课程名称！', offset: 80 });
    return;
  }
  const teacherId = userManager.getUserId();
  if (!teacherId) {
    ElMessage.error({ message: '无法获取教师ID，请先登录！', offset: 80 });
    return;
  }
  if (!uploadedRawCoverImage.value) {
    ElMessage.warning({ message: '请上传课程封面图片！', offset: 80 });
    return;
  }


  submitting.value = true;
  const courseMetadata = { ...courseForm.value, teacherId };

  try {
    const response = await courseService.createCourse(courseMetadata, uploadedRawCoverImage.value);
    if (response.success) {
      ElMessage.success({ message: '新课程创建成功！', offset: 80 });
      resetForm();
      router.push('/my-course');
    } else {
      ElMessage.error({ message: '课程创建失败：' + (response.message || '服务器响应异常'), offset: 80 });
    }
  } catch (error) {
    console.error('创建课程过程中发生错误:', error);
    ElMessage.error({ message: '网络错误或服务器无响应，请稍后再试！', offset: 80 });
  } finally {
    submitting.value = false;
  }
};

// --- 重置表单 ---
const resetForm = () => {
  courseForm.value = { name: '', description: '', school: '', credit: 0 };
  uploadedRawCoverImage.value = null;
  coverImageList.value = [];
  if (coverImageUploadRef.value) {
    coverImageUploadRef.value.clearFiles();
  }
};

const goBack = () => {
  router.back();
};
</script>

<template>
  <div class="page-container">
    <div class="content-wrapper">
      <el-card class="page-header-card">
        <div class="page-header-content">
          <h2>创建新的课程</h2>
          <p>请填写课程的详细信息，开启您的教学之旅。</p>
        </div>
      </el-card>

      <el-card class="form-card">
        <el-form :model="courseForm" label-position="top" class="course-info-form">
          <el-row :gutter="30">
            <!-- 左侧表单区域 -->
            <el-col :xs="24" :sm="14">
              <el-form-item label="课程名称" required>
                <el-input v-model="courseForm.name" placeholder="例如：Vue 3 从入门到实战"></el-input>
              </el-form-item>

              <el-form-item label="开课院系">
                <el-input v-model="courseForm.school" placeholder="例如：计算机学院"></el-input>
              </el-form-item>

              <el-form-item label="课程描述">
                <el-input
                    v-model="courseForm.description"
                    type="textarea"
                    :rows="8"
                    placeholder="详细介绍课程内容、目标和特色"
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- 右侧表单区域 -->
            <el-col :xs="24" :sm="10">
              <el-form-item label="总学分">
                <el-input-number v-model="courseForm.credit" :min="0" :max="20" controls-position="right" style="width: 100%;" class="align-left-input"></el-input-number>
              </el-form-item>

              <el-form-item label="课程封面 (可选)">
                <el-upload
                    ref="coverImageUploadRef"
                    action="#"
                    list-type="picture-card"
                    :auto-upload="false"
                    :limit="1"
                    accept="image/*"
                    :file-list="coverImageList"
                    :on-change="handleCoverImageChange"
                    :on-remove="handleCoverImageRemove"
                    class="cover-image-uploader"
                >
                  <el-icon><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">建议尺寸 16:9</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider />

          <div class="action-buttons">
            <el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
            <el-button class="submit-btn" :loading="submitting" @click="submitForm">
              {{ submitting ? '创建中...' : '确认创建课程' }}
            </el-button>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px); /* 减去头部导航的高度 */
  padding: 24px;
  box-sizing: border-box;
}

/* 【布局修改】内容包裹器，用于居中和限制最大宽度 */
.content-wrapper {
  max-width: 960px;
  margin: 0 auto;
}

.page-header-card {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #6ea2d9, #409eff);
  color: white;
  text-align: center;
  border-radius: 16px;
  padding: 32px 24px;
  border: none;
  box-shadow: 0 8px 16px rgba(255, 154, 68, 0.2);
}

.page-header-card h2 {
  font-size: 28px;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-header-card p {
  font-size: 15px;
  opacity: 0.9;
}

.form-card {
  background-color: #fff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e9ecef;
}

.course-info-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #495057;
  font-weight: 500;
  margin-bottom: 6px !important;
}

.course-info-form .el-form-item {
  margin-bottom: 24px;
}

/* 【样式修复】上传组件样式，确保为正方形 */
.cover-image-uploader :deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
  line-height: 148px; /* 垂直居中图标 */
  border-radius: 8px;
  background-color: #f8f9fa;
  border: 1px dashed #ced4da;
  transition: border-color 0.3s, background-color 0.3s;
}

.cover-image-uploader :deep(.el-upload--picture-card):hover {
  border-color: #409eff;
  background-color: #fff7f0;
}

.cover-image-uploader :deep(.el-upload-list__item) {
  width: 148px;
  height: 148px;
  border-radius: 8px;
}

.el-upload__tip {
  font-size: 12px;
  color: #adb5bd;
  margin-top: 4px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 16px;
  padding-top: 24px;
  border-top: 1px solid #e9ecef;
}

.submit-btn {
  background: #409eff;
  color: white;
  border: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.submit-btn:hover {

  transform: translateY(-2px);
}
.align-left-input ::v-deep .el-input__inner {
  text-align: left;
  -webkit-appearance: none;
  -moz-appearance: textfield;
  line-height: 1;
}

@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }
  .content-wrapper {
    max-width: 100%;
  }
  .action-buttons {
    justify-content: center;
  }
}
</style>
